﻿using HomeCareLibrary.Core.DataContracts;
using HomeCareLibrary.Core.Dtos;
using HomeCareLibrary.DataAccess;
using HomeCareLibrary.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HomeCareLibrary.AppService.Mappers;

namespace HomeCareLibrary.AppService
{
    public class SponsorAppService : AppServiceBase
    {
        /// <summary>
        /// Checks the promo code.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public List<CTCheckPromoCodeDto> CheckPromoCode(CheckPromocodeRequest request)
        {
            var returnData = new List<CTCheckPromoCodeDto>();
            if (request == null || string.IsNullOrEmpty(request.PromoCode))
            {
                return returnData;
            }

            using (var unitOfWork = new UnitOfWork())
            {
                var repository = new Repository<CTCheckPromoCode>(unitOfWork);
                var queryParameter = string.Format("@paramPromoCode='{0}'", request.PromoCode.Replace("'", "''").Replace("\"", @""""));

                var promoCodeCheckData = repository.ExecuteFuntion("sp_App_Check_Promocode", queryParameter);
                if (promoCodeCheckData != null)
                {
                    promoCodeCheckData.ToList().ForEach(promoCodeCheck =>
                    {
                        returnData.Add(new CTCheckPromoCodeDto
                        {
                            promocode = !string.IsNullOrEmpty(promoCodeCheck.promocode) ? promoCodeCheck.promocode : null,
                            PromocodeCheck = !string.IsNullOrEmpty(promoCodeCheck.PromocodeCheck) ? promoCodeCheck.PromocodeCheck : null
                        });
                    });
                }
                return returnData;
            }
        }

        /// <summary>
        /// Do initial setup.
        /// </summary>
        /// <param name="sponsorData">The sponsor data.</param>
        /// <returns></returns>
        public List<CTInitialSetupResultDto> InitialSetup(SponsorData sponsorData)
        {
            var result = new List<CTInitialSetupResultDto>();
            using (var unitOfWork = new UnitOfWork())
            {
                var repository = new Repository<CTInitialSetupResult>(unitOfWork);
                var userRepo = new Repository<User_ID>(unitOfWork);
                string userName = "homewizard-";
                var randomData = new Random();

                // Generate random Username and Password and also check from DB for already existing
                do
                {
                    userName = userName + GetRandomString(randomData, 6);
                }
                while (userRepo.FirstOrDefault(x => x.user_name == userName) != null);

                // Generate random password
                var password = GetRandomString(randomData, 6);

                // Genarte the query parameter for running SP.
                var queryParameter = string.Format("@paramUserName='{0}',@paramPassword='{1}',@paramPromoCode={2},@paramAppMoAlertWeek={3},@paramAppMoAlertDay={4},@paramAppMoAlertHour={5},@paramAppMoAlertBadge={6},@paramAppMoAlertPopup={7}", userName, password, string.IsNullOrEmpty(sponsorData.promoCode) ? "null" : (object)string.Format("'{0}'", sponsorData.promoCode.Replace("'", "''")), sponsorData.appMoAlertWeek, sponsorData.appMoAlertDay, sponsorData.appMoAlertHour, sponsorData.appMoAlertBadge, sponsorData.appMoAlertPopup);
                return repository.ExecuteFuntion("sp_App_Initial_Setup", queryParameter).ToDTOs();
            }
        }

        /// <summary>
        /// Updates the user sponsor code.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <param name="sponsorCode">The sponsor code.</param>
        public void UpdateUserSponsorCode(int userId, string sponsorCode)
        {
            using (var unitOfWork = new UnitOfWork())
            {
                var repository = new Repository<User_ID>(unitOfWork);
                var user = repository.FirstOrDefault(x => x.user_id1 == userId);
                if (user != null)
                {
                    user.sponsor = sponsorCode;
                }
                unitOfWork.SaveChanges();
            }
        }

        /// <summary>
        /// Gets the sponsor input 345x data.
        /// </summary>
        /// <param name="sponsorCode">The sponsor code.</param>
        /// <returns></returns>
        public SponsorInputs345xDto GetSponsorInput345xData(string sponsorCode)
        {
            using (var unitOfWork = new UnitOfWork())
            {
                var repository = new Repository<SponsorInputs345x>(unitOfWork);
                return repository.FirstOrDefault(x => x.sponsor == sponsorCode).ToDTO();
            }
        }

        private string GetRandomString(Random rnd, int length)
        {
            string charPool = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
            StringBuilder rs = new StringBuilder();

            while (length > 0)
            {
                rs.Append(charPool[(int)(rnd.NextDouble() * charPool.Length)]);
                length--;
            }
            return rs.ToString();
        }
    }
}
